import React, {useState, useEffect} from 'react'

import {Menu, List, Avatar, Switch, Button, Form, Input, Upload, Space, message, Select, Modal, Row, Col, Divider, notification} from 'antd'

import {UploadOutlined} from '@ant-design/icons'

import defaultSettings from '../../../../defaultSettings.js'

import {Container} from './style'

import {connect} from 'react-redux'

import {changeUserInfo} from '../../../../store/actionCreators'

import md5 from 'js-md5'

import MyRequest from '../../../../request/my_request'
import LoginRequest from '../../../../request/login_request'

const my_request = new MyRequest()
const login_request = new LoginRequest()

let timer = null

function MySetting(props){
    const {userInfo, changeUserInfo} = props

    const [form] = Form.useForm()

    const [settingType, setSettingType] = useState('1')
    const [avatar, setAvatar] = useState('')
    const [passwordVisible, setPasswordVisible] = useState(false)

    const [loginPassword, setLoginPassword] = useState('')
    const [newEmail, setNewEmail] = useState('')
    const [newEmailCode, setNewEmailCode] = useState('')
    const [emailVisible, setEmailVisible] = useState(false)

    const [canSendMsg, setCanSendMsg] = useState(true) //是否可以发送验证码
    const [countDownNum, setCountDownNum] = useState(60) //倒计时
    const [codeLoading, setCodeLoading] = useState(false) //发送验证码loading

    const [prePassword, setPrePassword] = useState('')
    const [newPassword, setNewPassword] = useState('')
    const [confirmPassword, setConfirmPassword] = useState('')
    const [passwordLoading, setPasswordLoading] = useState(false)

    const [userInfoLoading, setUserInfoLoading] = useState(false)

    const layout = {
        labelCol: { span: 6 },
        wrapperCol: { span: 8 },
    }
    const tailLayout = {
        wrapperCol: { offset: 6, span: 8 },
    }

    //隐藏邮箱中间的内容
    const hideEmailCenter = (email) => {
        if(email){
            const emailFront = email.split('@')[0]
            const result = emailFront.substring(0, 2) + '******' + emailFront.substring(emailFront.length - 2) + '@' + email.split('@')[1]
            return result
        }
        return ''
    }

    const securityList = [
        {
            title: '账户密码',
            content: '密码仅有不少于6位的限制，建议密码中包含大小写字母以及数字',
            link: '修改',
            type: 'password'
        },
        // {
        //     title: '密保问题',
        //     content: '未设置密保问题，密保问题可有效保护账户安全',
        //     link: '设置'
        // },
        {
            title: '绑定邮箱',
            content: '邮箱【只能修改一次】，已绑定邮箱：' + hideEmailCenter(userInfo.email),
            link: '修改',
            type: 'email'
        },
        {
            title: '绑定手机',
            content: '暂不支持该功能',
            link: '',
            type: 'phone'
        }
    ]
    const newMsgList = [
        {
            title: '消息动态',
            content: '其他用户的消息将以站内信的形式通知',
            isOpen: false
        },
        {
            title: '系统消息',
            content: '系统消息将以站内信的形式通知',
            isOpen: true
        },
        {
            title: '待办提醒',
            content: '待办提醒将以站内信的形式通知',
            isOpen: false
        },
    ]

    useEffect(() => {
        form.setFieldsValue({
            username: userInfo.username,
            desc: userInfo.desc,
            profession: userInfo.profession,
            company: userInfo.company,
            school: userInfo.school,
            blog: userInfo.blog,
            github: userInfo.github,
            phone: userInfo.phone,
            tags: userInfo.tags ? userInfo.tags.split(',') : []
        })
        setAvatar(userInfo.avatar)
        return () => {
            clearInterval(timer)
        }
    }, [userInfo])

    

    //发送验证码
    const sendMsgCode = () => {
        if(newEmail){
            if(!new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$").test(newEmail)){
                return message.warning('邮箱格式不正确！')
            }
        }else{
            return message.warning('请填写邮箱号')
        }

        setCodeLoading(true)

        checkNewEmail().then(res => {
            login_request.sendEmail({
                email: newEmail
            }).then(res => {
                message.success('邮箱验证码发送成功！')
                startCountDown()
            }).finally(() => {
                setCodeLoading(false)
            })
        }).catch(() => {
            setCodeLoading(false)
        })
    }

    //开始倒计时
    const startCountDown = () => {
        setCanSendMsg(false)
        let time = countDownNum
        timer = setInterval(() => {
            if(time > 0){
                time = time - 1
                setCountDownNum(time)
            }else{
                setCanSendMsg(true)
                clearInterval(timer)
            }
        }, 1000)
    }

    //图片上传之前
    const beforeUpload = (file) => {
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = (e) => {
            if(e.total > 3 * 1024 * 1024) return message.warning('图片不能超过3M！')
            setAvatar(e.target.result)
        }
        return false
    }

    //修改基础信息
    const confirmModify = (values) => {
        setUserInfoLoading(true)
        my_request.setUserInfo({
            ...values,
            avatar,
            tags: values.tags.join(',')
        }).then(res => {
            message.success('设置成功！')
            changeUserInfo({
                ...userInfo,
                ...values,
                avatar,
                tags: values.tags.join(',')
            })
        }).finally(() => {
            setUserInfoLoading(false)
        })
    }
    //打开安全设置的模态框
    const openSafeSettingModal = (type) => {
        if(type === 'password'){
            setPasswordVisible(true)
        }else if(type === 'email'){
            if(userInfo.rest_modify_count > 0){
                setEmailVisible(true)
            }else{
                message.error('操作失败！邮箱剩余修改次数为 0 次')
            }
        }
    }
    //取消修改密码
    const handlePasswordCancel = () => {
        setPasswordVisible(false)
        setPrePassword('')
        setNewPassword('')
        setConfirmPassword('')
    }
    //确认修改密码
    const handlePasswordOk = () => {
        if(!prePassword) return message.warning('请输入原密码！')
        if(!newPassword) return message.warning('请输入新密码！')
        if(!confirmPassword) return message.warning('请确认密码')

        if(newPassword.trim().length < 6) return message.warning('新密码太短！')

        if(newPassword !== confirmPassword) return message.warning('两次密码输入不一致！')

        setPasswordLoading(true)
        my_request.modifyPassword({
            prePassword: md5(prePassword),
            newPassword: md5(newPassword)
        }).then(res => {
            message.success('密码修改成功！')
            setPasswordVisible(false)
            setPrePassword('')
            setNewPassword('')
            setConfirmPassword('')
        }).finally(() => {
            setPasswordLoading(false)
        })
    }
    //取消修改邮箱
    const handleEmailCancel = () => {
        setLoginPassword('')
        setNewEmail('')
        setNewEmailCode('')
        setEmailVisible(false)
    }
    //检查邮箱是否可用
    const checkNewEmail = () => {
        return new Promise((resolve, reject) => {
            my_request.isEmailBeRegister({
                email: newEmail
            }).then(res => {
                if(res === '2'){
                    reject()
                    message.warning('邮箱已经被注册！')
                }else if(res === '1'){
                    resolve()
                }
            })
        })
    }
    //确认修改密邮箱
    const handleEmailOk = () => {
        Modal.confirm({
            title: '是否确认本次操作？',
            content: '绑定邮箱只能修改一次！请谨慎抉择',
            okText: '知道了，仍要修改',
            confirmLoading: false,
            onOk(){
                return new Promise((resolve, reject) => {

                    if(newEmail){
                        if(!new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$").test(newEmail)){
                            resolve()
                            return message.warning('邮箱格式不正确！')
                        }
                    }else{
                        resolve()
                        return message.warning('请填写邮箱号')
                    }

                    if(!loginPassword){
                        resolve()
                        return message.warning('请输入登录密码')
                    }

                    if(!newEmailCode){
                        resolve()
                        return message.warning('请输入验证码')
                    }

                    my_request.modifyEmail({
                        password: md5(loginPassword),
                        newEmail,
                        newEmailCode
                    }).then(res => {
                        resolve()
                        setEmailVisible(false)
                        setLoginPassword('')
                        setNewEmail('')
                        setNewEmailCode('')
                        notification.success({
                            message: '新邮箱绑定成功！',
                            description: '原邮箱已注销，新邮箱现已可用于登录本站，邮箱仅支持修改一次，如特殊原因需再次修改，请联系管理员',
                            duration: 0
                        })
                        changeUserInfo({
                            ...userInfo,
                            rest_modify_count: userInfo.rest_modify_count - 1,
                            email: newEmail
                        })
                    })
                })
            }
        });
    }
    return (
        <Container>
            <Menu
                style={{ width: 256 }}
                defaultSelectedKeys={[settingType]}
                mode="inline"
                theme="light"
                onClick={(e) => setSettingType(e.key)}
            >
                <Menu.Item key="1">
                    基本设置
                </Menu.Item>
                <Menu.Item key="2">
                    安全设置
                </Menu.Item>
                <Menu.Item key="3">
                    新消息通知
                </Menu.Item>
            </Menu>
            <div className="content">
                <div className="title">{settingType === '1' ? '基本设置' : settingType === '2' ? '安全设置' : '新消息通知'}</div>
                {
                    settingType === '1' ? 
                    <Form
                        {...layout}
                        form={form}
                        onFinish={confirmModify}
                    >
                        <Form.Item
                            label="头像"
                        >
                            <Space size="large">
                                <Avatar size={80} src={avatar || defaultSettings.defaultAvatar}></Avatar>
                                <Upload accept="image/*" beforeUpload={beforeUpload} showUploadList={false}>
                                    <Button icon={<UploadOutlined />}>更换头像</Button>
                                </Upload>
                            </Space>
                        </Form.Item>
                        <Form.Item
                            label="用户名"
                            name="username"
                            rules={[{ required: true, message: '请填写你的用户名!' }]}
                        >
                            <Input placeholder="请输入用户名" maxLength={10} style={{width: 220}}/>
                        </Form.Item>
                        <Form.Item
                            label="个人简介"
                            name="desc"
                        >
                            <Input.TextArea placeholder="请输入个人简介" maxLength={50} style={{width: 220}} rows={4}/>
                        </Form.Item>
                        <Form.Item
                            label="职业"
                            name="profession"
                        >
                            <Input placeholder="请输入职业" style={{width: 220}}/>
                        </Form.Item>
                        <Form.Item
                            label="公司"
                            name="company"
                        >
                            <Input placeholder="请输入公司名称" style={{width: 220}}/>
                        </Form.Item>
                        <Form.Item
                            label="学校"
                            name="school"
                        >
                            <Input placeholder="请输入学校名称" style={{width: 220}}/>
                        </Form.Item>
                        <Form.Item
                            label="博客"
                            name="blog"
                        >
                            <Input placeholder="请输入博客地址" style={{width: 220}}/>
                        </Form.Item>
                        <Form.Item
                            label="GitHub"
                            name="github"
                        >
                            <Input placeholder="请输入github地址" style={{width: 220}}/>
                        </Form.Item>
                        <Form.Item
                            label="联系方式"
                            name="phone"
                        >
                            <Input placeholder="请输入联系方式" style={{width: 220}}/>
                        </Form.Item>
                        <Form.Item
                            label="个人标签"
                            name="tags"
                        >
                            <Select
                                mode="tags"
                                placeholder="请输入标签并回车"
                                style={{ width: '100%' }}
                                dropdownStyle={{display: 'none'}}
                            >
                            </Select>
                        </Form.Item>
                        <Form.Item {...tailLayout}>
                            直接输入标签并按下回车
                        </Form.Item>
                        <Form.Item {...tailLayout}>
                            <Button type="primary" htmlType="submit" loading={userInfoLoading}>
                            更新基本信息
                            </Button>
                        </Form.Item>
                    </Form> : 
                    settingType === '2' ? 
                    <List
                        itemLayout="horizontal"
                        dataSource={securityList}
                        renderItem={item => (
                        <List.Item>
                            <List.Item.Meta
                            title={item.title}
                            description={item.content}
                            />
                            <div>
                                <Button type="link" onClick={() => openSafeSettingModal(item.type)}>{item.link}</Button>
                            </div>
                        </List.Item>
                        )}
                    /> : 
                    settingType === '3' ? 
                    <List
                        itemLayout="horizontal"
                        dataSource={newMsgList}
                        renderItem={item => (
                        <List.Item>
                            <List.Item.Meta
                            title={item.title}
                            description={item.content}
                            />
                            <div>
                                <Switch checked={item.isOpen} checkedChildren="开" unCheckedChildren="关"/>
                            </div>
                        </List.Item>
                        )}
                    /> : ''
                }
            </div>
            <Modal
                title="修改密码"
                visible={passwordVisible}
                onOk={handlePasswordOk}
                onCancel={handlePasswordCancel}
                confirmLoading={passwordLoading}
                okText="确认修改"
            >
                <div style={{marginLeft: 36}}>
                    <Row align="middle" gutter={[0, 16]}>
                        <Col span={4}>原密码：</Col>
                        <Col span={8}>
                            <Input placeholder="请输入原密码" type="password" value={prePassword} onChange={(e) => setPrePassword(e.target.value)} style={{width: 180}}/>
                        </Col>
                    </Row>
                    <Row align="middle" gutter={[0, 16]}>
                        <Col span={4}>新密码：</Col>
                        <Col span={8}>
                            <Input placeholder="请输入新密码" type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} style={{width: 180}}/>
                        </Col>
                    </Row>
                    <Row align="middle" gutter={[0, 16]}>
                        <Col span={4}>确认密码：</Col>
                        <Col span={8}>
                            <Input placeholder="请确认新密码" type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} style={{width: 180}}/>
                        </Col>
                    </Row>
                </div>
            </Modal>
            <Modal
                title="修改绑定邮箱"
                visible={emailVisible}
                onOk={handleEmailOk}
                onCancel={handleEmailCancel}
                okText="确认永久修改"
            >
                <div style={{marginLeft: 36}}>
                    <Row align="middle" gutter={[0, 16]}>
                        <Col span={24}>【温馨提示】绑定邮箱只能修改一次，请谨慎抉择。</Col>
                    </Row>
                    <Divider />
                    <Row align="middle" gutter={[0, 16]}>
                        <Col span={6}>当前邮箱账号：</Col>
                        <Col span={8}>
                            {hideEmailCenter(userInfo.email)}
                        </Col>
                    </Row>
                    <Row align="middle" gutter={[0, 16]}>
                        <Col span={6}>账号登录密码：</Col>
                        <Col span={8}>
                            <Input placeholder="请输入登录密码" type="password" value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)} style={{width: 180}}/>
                        </Col>
                    </Row>
                    <Divider />
                    <Row align="middle" gutter={[0, 16]}>
                        <Col span={6}>新绑定邮箱：</Col>
                        <Col span={10}>
                            <Input placeholder="请输入新邮箱" value={newEmail} onChange={(e) => setNewEmail(e.target.value)} style={{width: 180}}/>
                        </Col>
                    </Row>
                    <Row align="middle" gutter={[0, 16]}>
                        <Col span={6}>新邮箱验证码：</Col>
                        <Col span={8}>
                            <Input placeholder="请输入验证码" value={newEmailCode} onChange={(e) => setNewEmailCode(e.target.value)} style={{width: 136}}/>
                        </Col>
                        <Col span={6}>
                            <Button type="primary" ghost loading={codeLoading} disabled={!canSendMsg} onClick={sendMsgCode}>发送验证码 {canSendMsg ? '' : (countDownNum + 's')}</Button>
                        </Col>
                    </Row>
                </div>
            </Modal>
        </Container>
    )
}

const mapState = (state) => ({
    userInfo: state.userInfo
})

const mapDispatch = (dispatch) => ({
    changeUserInfo(data){
		dispatch(changeUserInfo(data))
	}
})

export default connect(mapState, mapDispatch)(MySetting)